// jfx bridge: js call jfx
if (!window.jfx) {
    window.jfx = {
        require : function (action, params) {}
    }
}

if (!window.d) {
    window.d = function (msg) {
        console.log (msg);
    };
}

// local bridge: 
let bridge = (function () {
    function changeConsole () {
        console.log = function (message) {
            jfx.log (message);
        };
        console.error = function (message) {
            jfx.error (message);
        }
    }

    function delegate (name, args) {
        let temp = window [name], type = (typeof temp);
        // console.log ('......................... [' + type + '] ' + temp + '..........................');
        if ((name in window) && (typeof window[name] === 'function')) {
            console.log ('delegating function: ' + name + ' with args: ' + args);

            return window[name].apply (window, args);
        } else {
            console.log ('the delegated function: ' + name + ' not found. ignore it!');
        }
    }

    return {
        confirm_close : function () {
            console.log ('confirming page close ...');
            let ret = delegate ('on_close', arguments);
            return ret === undefined || ret === null ? true : ret;
        },
        init_page : function () {
            // at first, bridge the console.log to jfx.log
            changeConsole ();
            // now, the console.log will show the log in jfx

            // updating web-ui use set locale
            delegate ('update_ui');
        },
        fire_page_load : function () {
            // console.log ('fire page load...');
            delegate ('on_page_load', arguments);
        },
        require : function (action, params) {
            let o;
            // params = (params === undefined || params === null) ? '' : params;
            params = (params === undefined) ? null : params;
            if (!(params instanceof Date) && (typeof params === 'object')) {
                params = JSON.stringify (params);
            }
            try {
                o = jfx.require (action, params);
            } catch (ex) {
                console.error (ex);
                throw ex;
            }
            if (o !== null && o !== undefined) {
                o = JSON.parse (o);
                if (o.code !== 0)
                    throw o.data;
                return o.data;
            }
        }
    };
})();

$(function () {
    // disable all text selection
    // $(window).on ('selectstart', function () {return false;});
});